<template>
  <div>
    <!-- 顶部实时概况数据 -->
    <MemberTimeData />

    <!-- 数据表格 start -->
    <el-card class="mt-20">
      <!-- 搜索栏 -->
      <div class="pt-10 pb-10">
        <SearchForm
          :form-option="formOption"
          :show-btn="true"
          :showArrow="true"
          :btn-list="btnList"
          v-model="formOption.formData"
          label-width="90px"
        />
      </div>
      <PageTable
        :loading="loading"
        :data="dataSource"
        :columns="columns"
        :options="options"
        @selectChange="selectChange"
      />
      <Pagination
        v-show="total > 0"
        :total="total"
        :pageNo.sync="listQuery.pageNo"
        :pageSize.sync="listQuery.pageSize"
        :pageSizes="[10, 20, 30, 50, 100, 200, 500]"
        @pagination="getList"
      />
    </el-card>
    <!-- 数据表格 end -->

    <!-- 积分调整弹窗 -->
    <MemberPay v-model="dialogFormVisible" :id="editUserId" @refresh="getList" />

    <!-- 导出全部 -->
    <SelectEmail v-model="SelectEmailDialog" :type="exportType" @exportAll="handleExportAll" />
  </div>
</template>

<script>
import { export2Excel } from '@/utils/export'
import MemberPay from './components/MemberPay.vue'
import MemberTimeData from './components/MemberTimeData.vue'
import {
  REGISTER_WAY,
  REGISTER_PLATFORM,
  REGISTER_PLATFORM_SELECT,
  USER_ATTRIBUTE,
  USER_ATTRIBUTE_SELECT
} from '@/enum/user'

export default {
  name: 'MemberList',
  components: {
    // 实时数据
    MemberTimeData,
    // 积分弹窗
    MemberPay
  },
  data() {
    return {
      // 表单搜索配置
      formOption: {
        items: [
          {
            type: 'datetimerange',
            label: '注册时间',
            value: 'time'
          },
          {
            type: 'input',
            label: '昵称/手机',
            value: 'nickNameOrMobile'
          },
          {
            type: 'select',
            label: '注册平台',
            value: 'registerPlatform',
            selectList: REGISTER_PLATFORM_SELECT
          },
          {
            type: 'select',
            label: '会员属性',
            value: 'userAttribute',
            selectList: USER_ATTRIBUTE_SELECT
          }
        ],
        formData: {
          registerPlatform: '',
          userAttribute: ''
        }
      },
      avatar: require('@/assets/avatar.png'),
      SelectEmailDialog: false,
      exportType: 4,

      // 表单按钮列表
      btnList: [
        {
          type: 'primary',
          label: '搜索',
          onClick: () => {
            this.listQuery.pageNo = 1
            this.getList()
          }
        },
        {
          label: '重置',
          onClick: () => {
            this.formOption.formData = {}
            this.listQuery.pageNo = 1
            this.getList()
          }
        },
        {
          type: 'primary',
          label: '导出',
          onClick: () => {
            this.exportFile()
          }
        },
        {
          type: 'primary',
          label: '导出全部',
          loading: false,
          onClick: () => {
            this.exportFileByEmail()
          }
        }
      ],

      // 分页配置
      listQuery: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,

      // 表格加载
      loading: false,
      // 表格配置
      options: {
        border: true,
        select: true
      },
      // 表格列
      columns: [
        {
          label: '客户信息',
          width: '210px',
          render: (h, { row }) => {
            const index = row.profilePhoto.lastIndexOf('/')
            const avatar = row.profilePhoto.slice(index + 1)
            const flag = row.profilePhoto && avatar !== 'u_default.png'
            return (
              <div style={'display: flex'}>
                {flag ? (
                  <img style={'width: 60px;height: 60px;'} src={row.profilePhoto} />
                ) : (
                  <img style={'width: 60px;height: 60px;'} src={this.avatar} />
                )}
                <div
                  class="ml-10 pt-5 pb-5"
                  style={
                    'display: flex;flex-direction: column;justify-content: space-between;align-items:flex-start'
                  }
                >
                  <div class="flex justify-between">
                    <p>{row.nickName}</p>
                    {!row.isActivation ? (
                      <el-tag
                        class="ml-5"
                        size="mini"
                        type="danger"
                        effect="dark"
                        style="background:#ff5f00"
                      >
                        待激活
                      </el-tag>
                    ) : (
                      ''
                    )}
                  </div>
                  <p>{row.mobile}</p>
                </div>
              </div>
            )
          }
        },
        {
          label: '账户积分',
          prop: 'integralSum',
          render: (h, { row }) => {
            return (
              <div>
                <p>{row.integralSum || 0}</p>
                <p
                  style="color:#51b4f9;cursor: pointer;"
                  onClick={() => this.toIntegralList(row.id)}
                >
                  积分明细
                </p>
              </div>
            )
          }
        },
        { prop: 'openSum', label: '打开次数', width: '80px' },
        {
          label: '近期访问时间',
          prop: 'lastOpenTime',
          render: (h, { row }) => {
            return <div>{this.formatDate(row.lastOpenTime, true)}</div>
          }
        },
        {
          label: '上次消费时间',
          prop: 'lastConsumeTime',
          render: (h, { row }) => {
            return <div>{this.formatDate(row.lastConsumeTime, true)}</div>
          }
        },
        {
          label: '会员属性',
          prop: 'userAttribute',
          render: (h, { row }) => {
            return <div>{USER_ATTRIBUTE[row.userAttribute]}</div>
          }
        },
        {
          label: '注册平台',
          prop: 'registerPlatform',
          render: (h, { row }) => {
            const color = row.registerPlatform === 4 ? '#193675' : '#333'
            return <div style={{ color }}>{REGISTER_PLATFORM[row.registerPlatform]}</div>
          }
        },
        {
          label: '注册方式',
          prop: 'registerWay',
          render: (h, { row }) => {
            return <div>{REGISTER_WAY[row.registerWay]}</div>
          }
        },
        {
          label: '注册时间',
          prop: 'createdTime',
          render: (h, { row }) => {
            return <div>{this.formatDate(row.createdTime)}</div>
          }
        },
        {
          label: '操作',
          render: (h, { row }) => {
            return (
              <div>
                <el-button type="text" onClick={() => this.toUserDetail(row.id)}>
                  查看
                </el-button>
                {this.openWalletOperateFlag ? (
                  <el-button type="text" onClick={() => this.editIntegral(row.id)}>
                    积分操作
                  </el-button>
                ) : (
                  ''
                )}
              </div>
            )
          }
        }
      ],
      // 表格源数据
      dataSource: [],
      // 选择列表数据
      selectList: [],

      // 积分调整弹窗是否显示
      dialogFormVisible: false,
      //是否展示积分操作
      openWalletOperateFlag: false,
      // 调整积分用户id
      editUserId: ''
    }
  },
  mounted() {
    this.getList()
    this.handleOpenWalletOperateFlag()
  },
  methods: {
    //获取充值开关
    async handleOpenWalletOperateFlag() {
      const { data } = await this.$http.finance.userFinance.getOpenWalletOperateFlag()
      this.openWalletOperateFlag = data
    },
    // 导出全部
    async exportFileByEmail() {
      this.$confirm(
        '确定要导出全部吗？数据量较大会导出较慢，请耐心等待。请勿重复点击，如出现导出失败，请联系技术部门。',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          this.SelectEmailDialog = true
        })
        .catch(err => err)
    },
    // 获取用户列表
    async getList() {
      // 参数整理
      const params = {
        ...this.listQuery,
        nickNameOrMobile: this.formOption.formData?.nickNameOrMobile ?? '',
        registerPlatform: this.formOption.formData?.registerPlatform ?? '',
        userAttribute: this.formOption.formData?.userAttribute ?? '',
        startTime: this.formOption.formData.time?.[0] ?? '',
        endTime: this.formOption.formData.time?.[1] ?? ''
      }
      // 发送请求
      const {
        data: { records, total }
      } = await this.$http.user.user.getList({ params })
      this.dataSource = records
      this.total = total
    },

    // 时间转换
    formatDate(date) {
      if (!date) {
        return '暂无'
      }
      return date
    },

    /**
     * 勾选列表行数据
     * @parma {Array} rows 选中行
     */
    selectChange(rows) {
      this.selectList = rows
    },

    async handleExportAll(value) {
      const params = {
        email: value,
        nickNameOrMobile: this.formOption.formData?.nickNameOrMobile ?? '',
        registerPlatform: this.formOption.formData?.registerPlatform ?? '',
        userAttribute: this.formOption.formData?.userAttribute ?? '',
        startTime: this.formOption.formData.time?.[0] ?? '',
        endTime: this.formOption.formData.time?.[1] ?? ''
      }
      this.btnList[3].loading = true
      const res = await this.$http.user.user.exportUser({ params })
      if (res.status == 200) {
        this.btnList[3].loading = false
        this.$message.success('导出成功')
      }
    },

    // 点击导出
    exportFile() {
      if (!this.selectList.length) return this.$message.error('请选择要导出的数据')
      // 表头设置
      const headerData = this.columns.filter(item => item.prop).map(item => item.label)
      headerData.splice(0, 0, '用户名称')
      headerData.splice(1, 0, '电话号码')
      // 表格数据字段
      const filterData = this.columns.filter(item => item.prop).map(item => item.prop)
      filterData.splice(0, 0, 'nickName')
      filterData.splice(1, 0, 'mobile')
      // 表格数据
      const tableData = this.selectList.map(item => {
        return {
          ...item,
          integralSum: item.integralSum || 0,
          registerWay: REGISTER_WAY[item.registerWay],
          registerPlatform: REGISTER_PLATFORM[item.registerPlatform],
          userAttribute: USER_ATTRIBUTE[item.userAttribute],
          lastConsumeTime: item.lastConsumeTime || '暂无',
          lastOpenTime: item.lastOpenTime || '暂无'
        }
      })
      // console.log(tableData)
      export2Excel(headerData, tableData, filterData, '会员列表', () => {
        this.$message.success('导出成功')
      })
    },

    // 查看积分明细
    toIntegralList(id) {
      this.$router.push({
        name: 'MemberIntegral',
        query: { id }
      })
    },

    // 点击调整积分
    editIntegral(id) {
      this.dialogFormVisible = true
      this.editUserId = id
    },

    // 查看用户详情
    toUserDetail(id) {
      this.$router.push({
        name: 'MemberInfo',
        query: { id }
      })
    }
  }
}
</script>
